package android.apps.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.apps.R;
import android.apps.adapter.AlbumItemAdapter;
import android.apps.adapter.AlbumItemAdapter1;
import android.apps.adapter.AlbumItemAdapter2;
import android.apps.bean.ComparatorAddr;
import android.apps.bean.MadeListItem;
import android.apps.bean.MadeListItem2;
import android.apps.bean.PhotoUpImageBucket;
import android.apps.bean.PhotoUpImageItem;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.media.ExifInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

//这里面要用list嵌套gridview实现；
public class AlbumItemActivity extends Activity implements OnClickListener {

    private ListView listView;
    private TextView back, ok, swap;
    private PhotoUpImageBucket photoUpImageBucket;
    private ArrayList<PhotoUpImageItem> selectImages;
    private AlbumItemAdapter adapter;
    private List<PhotoUpImageItem> imageList;//这是原始的list；按时间排序，保留；
    private List<PhotoUpImageItem> imageListCopy = new ArrayList<PhotoUpImageItem>();//这是copy的list；按地点排序；

    private List<MadeListItem> madeList_addr = new ArrayList<MadeListItem>();

    private List<MadeListItem2> madeList_time = new ArrayList<MadeListItem2>();

    private String itemType = "";
    private boolean isShowAdrr = true;
    private AlbumItemAdapter2 adapter_addr;
    private AlbumItemAdapter1 adapter_time;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
//            adapter = new AlbumItemAdapter(imageList, AlbumItemActivity.this);
            if (dialog != null && dialog.isShowing())
                dialog.dismiss();
            adapter_addr = new AlbumItemAdapter2(madeList_addr, AlbumItemActivity.this);
            listView.setAdapter(adapter_addr);
        }
    };
    private ProgressDialog dialog;


    /**
     * 把 imageList 切成n个list；根据当中的address；
     */
    private void makeList() {

        //按时间；
        itemType = imageList.get(0).getDatatime();//第一个标签
        List<PhotoUpImageItem> imasdf2 = new ArrayList<PhotoUpImageItem>();//第2个列表
        Log.e("LCY", "初始imasdf2=" + imasdf2);
        for (int i = 0; i < imageList.size(); i++) {
            if (imageList.get(i).getDatatime().equals(itemType)) {
                imasdf2.add(imageList.get(i));
                Log.e("LCY", "imasdf2=" + imasdf2);
            } else {
                madeList_time.add(new MadeListItem2(imasdf2, itemType));
                itemType = imageList.get(i).getDatatime();//下一个标签
                imasdf2 = new ArrayList<PhotoUpImageItem>();//下一个列表
                imasdf2.add(imageList.get(i));
                Log.e("LCY", "新建的imasdf2=" + imasdf2);
            }
        }
//        按地点
        itemType = imageListCopy.get(0).getAddress();//第一个标签
        List<PhotoUpImageItem> imasdf = new ArrayList<PhotoUpImageItem>();//第一个列表

        for (int i = 0; i < imageList.size(); i++) {
            Log.e("LCy", "i=" + i);
            String x = (imageListCopy.get(i).getAddress() == null ? "" : imageListCopy.get(i).getAddress());
            if (itemType.equals(x)) {
                imasdf.add(imageListCopy.get(i));
                if (i == imageList.size() - 1) {
                    madeList_addr.add(new MadeListItem(imasdf, itemType));
                }
            } else {
                madeList_addr.add(new MadeListItem(imasdf, itemType));
                itemType = x;//下一个标签
                imasdf.add(imageListCopy.get(i));
                imasdf = new ArrayList<PhotoUpImageItem>();//下一个列表
            }
        }
        mHandler.sendEmptyMessage(1);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.album_item_images);
        init();
        setListener();
    }

    private void init() {
        listView = (ListView) findViewById(R.id.album_item_gridv);
        back = (TextView) findViewById(R.id.back);
        ok = (TextView) findViewById(R.id.sure);
        swap = (TextView) findViewById(R.id.swap);
        swap.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!isShowAdrr) {
//                    adapter = new AlbumItemAdapter(imageListCopy, AlbumItemActivity.this);
//                    listView.setAdapter(adapter);
                    if (adapter_addr == null)
                        adapter_addr = new AlbumItemAdapter2(madeList_addr, AlbumItemActivity.this);
                    listView.setAdapter(adapter_addr);
                    isShowAdrr = true;
                } else {
//                    adapter = new AlbumItemAdapter(imageList, AlbumItemActivity.this);
//                    listView.setAdapter(adapter);
                    if (adapter_time == null)
                        adapter_time = new AlbumItemAdapter1(madeList_time, AlbumItemActivity.this);
                    listView.setAdapter(adapter_time);
                    isShowAdrr = false;
                }
            }
        });
        selectImages = new ArrayList<PhotoUpImageItem>();

        Intent intent = getIntent();
        photoUpImageBucket = (PhotoUpImageBucket) intent.getSerializableExtra("imagelist");
        imageList = photoUpImageBucket.getImageList();
        sortListByAddr();
    }

    /**
     * 按时间排序；
     */
//    private void sortListByTime() {
//        ComparatorTime comparator = new ComparatorTime();
//        Collections.sort(imageList, comparator);//按时间排序；
//        for (int i = 0; i < imageList.size(); i++) {
//            PhotoUpImageItem photo = imageList.get(i);
//            Log.e("LCY", photo.getAddress() + "," + photo.getDatatime());
//        }
//        //排序完成；
//    }

    /**
     * 在分线程；
     * 按地点排序；
     */
    private void sortListByAddr() {
        dialog = new ProgressDialog(this);
        dialog.setMessage("加载中...");
        dialog.show();
        imageListCopy = new ArrayList<PhotoUpImageItem>(imageList);
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < imageListCopy.size(); i++) {
                    try {
                        PhotoUpImageItem photoUpImageItem = imageListCopy.get(i);
                        ExifInterface exif = new ExifInterface(photoUpImageItem.getImagePath());
                        String latitude_str = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE);// 纬度
                        String longitude_str = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);//经度；
                        String datetime = exif.getAttribute(ExifInterface.TAG_DATETIME);
                        if (datetime != null && datetime.length() >= 10) {
                            Log.e("LCY", "拍摄时间=" + datetime.substring(0, 10));
                            photoUpImageItem.setDatatime(datetime.substring(0, 10));
                        }
//                设置地名；
//                把地名放进去；
//                1按地名排序；对应的就是首字母；2.按时间；
//                按首字母展示，item为gridview；
                        if (longitude_str != null && latitude_str != null) {
                            String[] longitude2 = longitude_str.split(",");
                            String[] latitude2 = latitude_str.split(",");
                            double realLongitude = changeTo(longitude2[0], longitude2[1], longitude2[2]);
                            double realLatitude = changeTo(latitude2[0], latitude2[1], latitude2[2]);
                            Geocoder geocoder = new Geocoder(AlbumItemActivity.this);
                            List<Address> x1 = geocoder.getFromLocation(realLatitude, realLongitude, 1);
                            Log.e("LCY", "地理名字=" + x1.get(0).getAddressLine(0));
                            photoUpImageItem.setAddress(x1.get(0).getAddressLine(0));
                        } else {
                            photoUpImageItem.setAddress("");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                ComparatorAddr comparator = new ComparatorAddr();
                Collections.sort(imageListCopy, comparator);//按地点排序；
                for (int i = 0; i < imageListCopy.size(); i++) {
                    PhotoUpImageItem photo = imageListCopy.get(i);
                    Log.e("LCY", photo.getAddress() + "," + photo.getDatatime());
                }
                //排序完成；
                Log.e("LCY", "按地点排序完成");
                makeList();
            }
        }).start();
    }

    private double changeTo(String s, String s1, String s2) {
        double l1 = partDouble(s);
        double l2 = partDouble(s1);
        double l3 = partDouble(s2);
        double realNum = l1 + l2 / 60 + l3 / 3600;
        return realNum;
    }

    private double partDouble(String s) {
        String[] ss = s.split("/");
        int xxx = Integer.parseInt(ss[0]);
        int xxx2 = Integer.parseInt(ss[1]);
        double y = 1.0 * xxx / xxx2;
        return y;
    }

    private void setListener() {
        back.setOnClickListener(this);
        ok.setOnClickListener(this);
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                CheckBox checkBox = (CheckBox) view.findViewById(R.id.check);
                photoUpImageBucket.getImageList().get(position).setSelected(
                        !checkBox.isChecked());
                adapter.notifyDataSetChanged();
                Log.e("LCY", "这里面要用list嵌套gridview实现；");
                Toast.makeText(AlbumItemActivity.this, "相册的postion=" + position,
                        Toast.LENGTH_SHORT).show();
//				photoUpImageBucket.getImageList().get(position).setSelected(
//						!photoUpImageBucket.getImageList().get(position).isSelected());
//				adapter.notifyDataSetChanged();
                if (photoUpImageBucket.getImageList().get(position).isSelected()) {
                    if (selectImages.contains(photoUpImageBucket.getImageList().get(position))) {

                    } else {
                        selectImages.add(photoUpImageBucket.getImageList().get(position));
                    }
                } else {
                    if (selectImages.contains(photoUpImageBucket.getImageList().get(position))) {
                        selectImages.remove(photoUpImageBucket.getImageList().get(position));
                    } else {

                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.sure:
                Intent intent = new Intent(AlbumItemActivity.this, SelectedImagesActivity.class);
                intent.putExtra("selectIma", selectImages);
                startActivity(intent);
                break;

            default:
                break;
        }
    }

}
